﻿namespace Dispatcher.Models.Requests;

// 内存表
public class KeyPoolRepository
{
    private readonly object _o = new();

    private DynamicTable? _table;
    public KeyPoolRepository(DynamicTable table)
    {
        _table = table;
    }
    private volatile List<PoolKey> _poolKeys = new();
    public List<PoolKey> OpenPoolKeys
    {
        get
        {
            lock (_o)
            {
                return new List<PoolKey>(_poolKeys);
            }
        }
    }

    public void Transfer(List<PoolKey>? poolKeys)
    {
        try
        {
            _table?.Log($"尝试添加{poolKeys?.Count}个key");
            //lock (_o)
            //{
            //    var copy = new List<PoolKey>(_poolKeys);
            //    copy.Clear();
            //    _poolKeys = copy;
            //    _table.Log("清除了现有的key");
            //}
            if (poolKeys == null)
            {
                return;
            }
            //
            lock (_o)
            {
                var copy2 = new List<PoolKey>(poolKeys);
                _poolKeys = copy2;
            }
            
            //OpenPoolKeys.AddRange(poolKeys);
            _table?.Log($"添加了若干个key: {poolKeys.Count}");
        }
        catch (Exception e)
        {
            _table?.Log(e.Message);
        }
    }


    public void RemovePoolKey(PoolKey poolKey)
    {
        OpenPoolKeys.Remove(poolKey);
    }
    // public List<PoolKey> CanNotUseKeys { get; set; } = new();
    public int Count => OpenPoolKeys.Count;


    public void Add(PoolKey key)
    {
        var poolKey = OpenPoolKeys.FirstOrDefault(p => p.PoolKeyId == key.PoolKeyId);
        if (poolKey == null)
        {
            OpenPoolKeys.Add(key);
        }
        else
        {
            poolKey.CopyFrom(poolKey);
        }

    }


}